﻿

namespace CSharpLearningProject
{
    internal class ConcurrentPipeline
    {
        private readonly SemaphoreSlim _plcLock = new SemaphoreSlim(1, 1);

        public async Task RunFullPipelineAsync(CameraConfig config)
        {
            Console.WriteLine($"[{config.CameraId}] 开始执行 - 线程 {Thread.CurrentThread.ManagedThreadId}");

            // 1. 初始延时
            await Task.Delay(300);
            Console.WriteLine($"[{config.CameraId}] 初始延时完成");

            // 2. 相机拍照
            var image = await CaptureImageAsync(config);
            Console.WriteLine($"[{config.CameraId}] 拍照完成");

            // 3. 图像处理
            var result = await ProcessImageAsync(image);
            Console.WriteLine($"[{config.CameraId}] 图像处理完成");

            // 4. 处理完成后的延时
            await Task.Delay(300);
            Console.WriteLine($"[{config.CameraId}] 处理后延时完成");

            // 5. 调用PLC命令
            await _plcLock.WaitAsync();
            try
            {
                Console.WriteLine($"[{config.CameraId}] 开始PLC调用");
                await SendToPlcAsync(result);
                Console.WriteLine($"[{config.CameraId}] PLC调用完成");
            }
            finally
            {
                _plcLock.Release();
            }
        }

        private async Task<ImageData> CaptureImageAsync(CameraConfig config)
        {
            await Task.Delay(100); // 模拟拍照耗时
            return new ImageData { CameraId = config.CameraId };
        }

        private async Task<ProcessedResult> ProcessImageAsync(ImageData image)
        {
            await Task.Delay(200); // 模拟处理耗时
            return new ProcessedResult { CameraId = image.CameraId };
        }

        private async Task SendToPlcAsync(ProcessedResult result)
        {
            await Task.Delay(100); // 模拟PLC调用
        }
    }

    public class CameraConfig { public string CameraId { get; set; } }
    public class ImageData { public string CameraId { get; set; } }
    public class ProcessedResult { public string CameraId { get; set; } }
}
